package login

import (
	"encoding/json"
	"fmt"
	"log"
	"math/rand"
	"net/http"
	"src/pojo"
	"src/redis"
	"time"
)

// 获取手机号验证码
func GetPhoneCode(w http.ResponseWriter, r *http.Request)  {
	var result pojo.Resp
	query := r.URL.Query()
	phone := query["phone"][0]
	// 1.手机号校验
	// 2.获取随机验证码
	code := randCode()
	// 3. redis记录
	redis.SetMini(phone, code,5)
	// 4. 异步发送验证码
	go func() {
		// time.Sleep(time.Duration(10)*time.Second)
		send(phone, code)
	}()
	// 5.返回
	result.Msg = "success"
	result.Data = code
	if err := json.NewEncoder(w).Encode(result); err != nil {
		log.Fatal(err)
	}
}

// 调用第三方服务发送验证码
func send(phone string, code string)  {
	log.Println("手机号:" + phone + "发送验证码:" + code)
}

// 6位随机验证码
func randCode() string {
	rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
	rndCode := fmt.Sprintf("%06v", rnd.Int31n(1000000))
	fmt.Println(rndCode)
	return rndCode
}

// 校验验证码
func CheckCode(w http.ResponseWriter, r *http.Request)  {
	var result pojo.Resp
	var p pojo.Phone
	if err := json.NewDecoder(r.Body).Decode(&p); err != nil{
		r.Body.Close()
		log.Fatal(err)
	}
	getCode := redis.Get(p.Phone)

	if(getCode == p.Code){
		result.Data = true
		result.Msg = "success"
	}else {
		result.Data = false
		result.Msg = "fail"
	}

	if err := json.NewEncoder(w).Encode(result); err != nil {
		log.Fatal(err)
	}
}
